<template>
  <div>
    <div class="input-section">
      <div class="right">
        <el-input v-model="searchQuery" placeholder="请输入社团名" style="
          width: 500px;
          height: 40px;
          margin-bottom: 20px;
          margin-top: 20px;
        " :prefix-icon="Search" clearable />
        <el-button type="primary" @click="searchClub">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="button-group">
        <el-button @click="exportToExcel" type="success">导出 Excel</el-button>
        <input type="file" @change="importFromExcel" accept=".xlsx, .xls" style="display: none;" ref="fileInputRef" />
        <el-button @click="handleFileInputClick" type="warning">导入 Excel</el-button>

        <el-button type="primary" @click="openAddDialog">新增</el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
      </div>
    </div>
    <el-table ref="tableRef" :data="tableData" style="width: 100%; height: 550px" row-key="id"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column prop="id" label="社团id" width="60" />
      <el-table-column prop="clubName" label="社团名称" width="120" />
      <el-table-column prop="userName" label="社长" width="100" />
      <el-table-column
  prop="tags"
  label="标签"
  width="100"
  :filters="tagFilters"
  column-key="tags"
  :filter-method="filterTag"
  filter-placement="bottom-end"
>
  <template #default="{ row }">
    <el-tag v-for="tag in row.tags" :key="tag">{{ tag }}</el-tag>
  </template>
</el-table-column>
      <el-table-column prop="introduction" label="社团简介" width="250" />
      <el-table-column label="社团成员" width="100">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="goToMemberPage(row.id)">
            查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="社团创建时间" sortable width="100" />
      <el-table-column prop="updateTime" label="更新时间" sortable width="100" />
      <el-table-column prop="isDelete" label="是否删除" width="80">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.isDelete === 0">正常</el-tag>
          <el-tag type="danger" v-else>已删除</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="handleView(row)">查看</el-button>
          <el-button size="small" @click="handleEdit(row)" type="primary">编辑</el-button>
          <el-popconfirm title="确认删除吗？" @confirm="() => handleDelete(row.id)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-section">
      <span class="record-count">共查询到 {{ total }} 条记录</span>
      <el-pagination background layout="prev, pager, next" :total="total" v-model:page-size="pageSize"
        v-model:current-page="currentPage" :page-sizes="[4, 10, 20, 50]" @current-change="loadTableData"
        @size-change="loadTableData" />
    </div>
    <el-dialog :title="isEditMode ? '编辑社团信息' : '新增社团信息'" v-model="dialogVisible" width="600px" @close="handleClose">
      <el-form :model="form" label-width="100px">
        <el-form-item label="社团名称">
          <el-input v-model="form.clubName" placeholder="请输入社团名称" />
        </el-form-item>
        <el-form-item label="社长ID">
          <el-input v-model="form.userId" placeholder="请输入社长ID" />
        </el-form-item>
        <!-- 只在编辑模式下显示标签选择 -->
        <el-form-item v-if="isEditMode" label="标签">
          <el-select v-model="form.tags" multiple placeholder="请选择标签" style="width: 100%">
            <el-option label="公益类" value="公益类" />
            <el-option label="科技类" value="科技类" />
            <el-option label="艺术类" value="艺术类" />
            <el-option label="文化类" value="文化类" />
            <el-option label="娱乐类" value="娱乐类" />
            <el-option label="职业发展类" value="职业发展类" />
            <el-option label="其他类" value="其他类" />
          </el-select>
        </el-form-item>
        <el-form-item label="社团简介">
          <el-input type="textarea" v-model="form.introduction" placeholder="请输入社团简介" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from "@element-plus/icons-vue";
import { getClubListAllAPI } from "@/apis/club";
import { updateClubAPI } from "@/apis/club"
import { addClubAPI } from "@/apis/club";
import { useRouter } from "vue-router";
import { deleteClubAPI } from "@/apis/club";
import { batchDeleteClubsAPI } from "@/apis/club";
import * as XLSX from 'xlsx';
const router = useRouter();

interface Club {
  id: number;
  clubName: string;
  userName: string;
  tags: string;
  introduction: string;
  memberCount: number;
  createTime: string;
  updateTime: string;
}
const handleCheckboxChange = (value: string[]) => {
  console.log("选中的标签:", value);
};
const tableData = ref<Club[]>([]); // 初始化为数组
const currentPage = ref(1);
const pageSize = ref(7);
const searchQuery = ref("");
const total = ref(0);
// typescript加类型声明
const filterTag = (value: string, row: any) => {
  return Array.isArray(row.tags) && row.tags.includes(value);
};
// 加载全部社团列表
const loadTableData = async () => {
  try {
    const response = await getClubListAllAPI(
      currentPage.value,
      pageSize.value,
      null
    );

    if (response.code === 0) {
      tableData.value = (response.data?.records || []).map(item => ({
  ...item,
  tags: Array.isArray(item.tags)
    ? item.tags
    : (typeof item.tags === 'string' && item.tags ? JSON.parse(item.tags) : [])
}));
      total.value = response.data?.total || 0;
    }
  } catch (error) {
    console.error("加载数据失败:", error);
  }
};

// 按名字搜索社团
const searchClub = async () => {
  if (!searchQuery.value) {
    ElMessage.warning("请输入社团ID");
    return;
  }

  try {
    const response = await getClubListAllAPI(
      1, // 搜索时重置到第一页
      pageSize.value,
      String(searchQuery.value) // 传入具体的ID值
    );

    if (response.code === 0) {
      tableData.value = response.data?.records || [];
      total.value = response.data?.total || 0;

      if (tableData.value.length === 0) {
        ElMessage.warning("未找到匹配的社团");
      }
    }
  } catch (error) {
    ElMessage.error("搜索失败");
    console.error('Search error:', error);
  }
};

const goToMemberPage = (clubId: number) => {
  router.push({
    name: 'clubMember', // 使用定义的路由名称
    params: { clubId }
  });
};
// 重置搜索
const resetSearch = () => {
  searchQuery.value = "";
  currentPage.value = 1;
  loadTableData(); // 调用获取全部的方法
};

onMounted(() => {
  loadTableData(); // 组件挂载时加载数据
});

const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个社团吗？`,
      '批量删除确认',
      { confirmButtonText: '确认删除', cancelButtonText: '取消', type: 'warning' }
    );

    const userId = 123; // 应从store获取实际用户ID
    const deleteList = selectedRows.value.map(row => ({ clubId: row.id, userId }));

    const response = await batchDeleteClubsAPI(deleteList);

    // 修改响应判断逻辑
    if (response.code === 0) {
      // 成功处理
      ElMessage.success(`成功删除 ${deleteList.length} 个社团`);

      // 立即更新本地状态（避免刷新）
      tableData.value = tableData.value.map(item => {
        if (selectedRows.value.some(row => row.id === item.id)) {
          return { ...item, isDelete: 1 }; // 标记为已删除
        }
        return item;
      });

      selectedRows.value = [];
    } else {
      // 特殊处理业务限制错误
      if (response.code === 50001) {
        throw new Error(response.message || '存在未结束活动，无法删除');
      } else {
        throw new Error(response.message || '批量删除失败');
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败详情:', error);
      ElMessage.error(error.message || '批量删除失败');
    }
  }
};

const fileInputRef = ref<HTMLInputElement | null>(null);
// 导出为 Excel
const exportToExcel = () => {
  if (!tableData.value.length) {
    ElMessage.warning('没有可导出的数据');
    return;
  }
  console.log("表格数据：", tableData.value);
  // 提取你想要导出的字段
  const exportData = tableData.value.map((item) => ({
    '社团ID': item.id,
    '社团名称': item.clubName,
    '社长': item.userName || '未知',
    '社团简介': item.introduction || '暂无简介',
    '标签': item.tags || '未知',
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '社团信息');

  // 下载 Excel 文件
  XLSX.writeFile(workbook, `社团列表_${new Date().toISOString().slice(0, 10)}.xlsx`);
};

// 导入 Excel

const handleFileInputClick = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click();
  } else {
    console.error("fileInputRef 未正确绑定");
    ElMessage.error("无法打开文件选择器，请检查代码");
  }
};

const importFromExcel = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const files = target.files;

  if (!files || files.length === 0) {
    ElMessage.warning("请选择一个 Excel 文件");
    return;
  }

  const file = files[0];
  const reader = new FileReader();

  interface ExcelRow {
    社团名称: string;
    社长ID: number; // 这里假设“社长”列是 userId
    社团简介: string;
  }

  reader.onload = async (e) => {
    const data = new Uint8Array(e.target?.result as ArrayBuffer);
    const workbook = XLSX.read(data, { type: "array" });
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];

    const jsonData = XLSX.utils.sheet_to_json(worksheet);
    console.log("Excel 导入的数据：", jsonData);

    let successCount = 0;
    let failCount = 0;

    for (const row of jsonData as ExcelRow[]) {
      try {
        const response = await addClubAPI(
          row['社团名称'],
          Number(row['社长ID']),
          row['社团简介']
        );
        if (response.code === 0) {
          successCount++;
        } else {
          failCount++;
          console.warn("添加失败：", response.message);
        }
      } catch (error) {
        failCount++;
        console.error("请求异常：", error);
      }
    }

    // 只在全部导入完成后提示和刷新
    ElMessage.success(`导入完成：成功 ${successCount} 条，失败 ${failCount} 条`);
    await loadTableData();
  };

  reader.readAsArrayBuffer(file);
};


const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定删除该社团吗？', '警告', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await deleteClubAPI(id);

    // 修改这里的判断条件
    if (response.code === 0) {
      ElMessage.success('删除成功');
      // 从本地数据中移除
      const index = tableData.value.findIndex(item => item.id === id);
      if (index !== -1) {
        tableData.value.splice(index, 1);
        total.value -= 1;
      }
      // 可选：重新加载数据确保状态一致
      loadTableData();
    } else {
      throw new Error(response.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败详情:', error);
      ElMessage.error(error.message || '删除失败');
    }
  }
};

const isEditMode = ref(false);

const openAddDialog = () => {
  isEditMode.value = false;
  form.value = {
    id: 0, // 新增时 id 为 0
    clubName: "",
    userId: 0,
    introduction: "",
    tags: [] // 初始化 tags 为空数组
  };
  dialogVisible.value = true;
};

const tableRef = ref<any>();
const dialogVisible = ref(false);
const selectedRows = ref<Club[]>([]); // 存储选中的行
const tagFilters = [
  { text: "公益类", value: "公益类" },
  { text: "科技类", value: "科技类" },
  { text: "艺术类", value: "艺术类" },
  { text: "文化类", value: "文化类" },
  { text: "娱乐类", value: "娱乐类" },
  { text: "职业发展类", value: "职业发展类" },
  { text: "其他类", value: "其他类" },
];
const handleView = (row: Club) => {
  router.push({
    path: '/manage/club/details',
    query: {
      clubId: row.id, // 传递社团 ID
    },
  });
};

const form = ref({
  id: 0,
  clubName: "",
  userId: 0,
  tags: [], // 确保 tags 是数组
  introduction: "",
});
const handleEdit = (row: Club) => {
  isEditMode.value = true;
  form.value = { ...row };
  dialogVisible.value = true;
};

const saveEdit = async () => {
  try {
    const { id, clubName, userId, introduction } = form.value;

    if (!clubName || !userId || !introduction) {
      ElMessage.warning("请填写完整的社团信息");
      return;
    }

    let response;
    if (!isEditMode.value) {
      // 新增逻辑
      response = await addClubAPI(clubName, userId, introduction);
    } else {
      // 编辑逻辑
      response = await updateClubAPI(id, clubName, userId, form.value.tags, introduction);
    }

    if (response.code === 0) {
      ElMessage.success(isEditMode.value ? "编辑社团成功" : "新增社团成功");
      dialogVisible.value = false;
      loadTableData();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  }
};

const handleClose = () => {
  dialogVisible.value = false;
  form.value = {
    id: 0,
    clubName: "",
    userId: 0,
    tags: [],
    introduction: "",
  };
};

const handleSelectionChange = (rows: Club[]) => {
  selectedRows.value = rows;
}
</script>

<style scoped>
.input-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right {
  display: flex;
  align-items: center;
  gap: 10px;
  /* 调整输入框和按钮间距 */
}

.button-group {
  display: flex;
  gap: 10px;
  /* 调整按钮间距 */
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.record-count {
  font-size: 14px;
  color: #666;
}

.el-table {
  margin-bottom: 20px;
}

.el-pagination {
  justify-content: center;
}
</style>
